package com.wang.sap.util;

import com.sap.conn.jco.*;
import com.sap.conn.jco.ext.DestinationDataProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @author wanggang
 * @date 2023/3/2
 */
@Slf4j
public class SapUtils {

    public static JCoFunction getJCoFunction(JCoDestination jCoDestination, String functionName) throws JCoException {
        JCoFunctionTemplate functionTemplate = jCoDestination.getRepository().getFunctionTemplate(functionName);
        return functionTemplate.getFunction();
    }

    /**
     * 获取JCoDestination
     * @param functionName  SAP接口名称
     * @return JCoDestination
     */
    public static JCoDestination getJcoConnection(String functionName) throws Exception {
        Properties properties = new Properties();
        properties.setProperty(DestinationDataProvider.JCO_ASHOST, "127.0.0.1");//sap服务器地址
        properties.setProperty(DestinationDataProvider.JCO_SYSNR, "00");//系统编号，找SAP核对写00就可以了
        properties.setProperty(DestinationDataProvider.JCO_CLIENT, "800");//集团号，不知道就问你们的sap basis
        properties.setProperty(DestinationDataProvider.JCO_USER, "itport");//帐号
        properties.setProperty(DestinationDataProvider.JCO_PASSWD, "Kd02779!");//密码
        properties.setProperty("jco.client.lang", "zh");    //语言

        //使用连接池
        properties.setProperty("jco.destination.peak_limit", "10"); //最大活动连接数,0表示无限制
        properties.setProperty("jco.destination.pool_capacity", "3");   //空闲连接数，如果为0，则没有连接池效果，默认为1
        log.info("properties = " + properties.toString());

        //生成配置文件，JCoDestinationManager.getDestination()调用时会需要该连接配置文件，后缀名需要为jcoDestination
        FileOutputStream fos = null;
        String suffix = "jcoDestination";
        File cfg = new File(functionName + "." + suffix);
        if (!cfg.exists()) {
            try {
                fos = new FileOutputStream(cfg, false);
                properties.store(fos, "for tests only !");
                fos.close();
            } catch (Exception var9) {
                throw new Exception("Unable to create the destination file " + cfg.getName(), var9);
            } finally {
                if (null != fos) {
                    fos.close();
                }
            }
        }
        return JCoDestinationManager.getDestination(functionName);
    }


}
